<template>
  <!-- 门诊挂号 -->
  <div>
    <!-- 患者信息搜索开始 -->
    <el-card class="box-card">
      <el-form ref="queryForm" :model="patientParams" label-width="70px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="身份证号" porp="idCard">
              <el-input v-model="patientParams.idCard" placeholder="请输入患者身份证号" clearable size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleIdCardQuery">加载身份证号</el-button>
              <el-button type="warning" icon="el-icon-search" size="mini" @click="handleIdCardQuery">加载患者信息</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleIdCardNull">清空</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 患者信息搜索结束 -->

    <!-- 患者基本信息表单开始 -->
    <el-card class="box-card">
      <el-form ref="form" :model="patientParams" :rules="rules" :inline="true" label-width="88px">
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="patientParams.idCard" placeholder="请输身份证号" clearable size="small" style="width:200px" />
        </el-form-item>
        <el-form-item label="患者姓名" prop="name">
          <el-input v-model="patientParams.name" placeholder="请输入患者姓名" clearable size="small" style="width:200px" />
        </el-form-item>
        <el-form-item label="患者电话" prop="phone">
          <el-input v-model="patientParams.phone" placeholder="请输入患者电话" clearable size="small" style="width:200px" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="patientParams.sex">
            <el-radio v-for="d in sexOptions" :key="d.dictValue" :label="d.dictValue" :value="d.dictValue">
              {{ d.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker v-model="patientParams.birthday" size="small" style="width:200px" value-format="yyyy-MM-dd"
            type="date" />
        </el-form-item>
        <el-form-item label="患者年龄" prop="age">
          <el-input v-model="patientParams.age" :readonly="true" placeholder="请输入患者年龄" clearable size="small"
            style="width:200px" />
        </el-form-item>
        <el-form-item label="地址信息" prop="address">
          <el-input v-model="patientParams.address" placeholder="请输入地址信息" clearable style="width:500px" size="small" />
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 患者基本信息表单结束 -->

    <!-- 挂号项目栏开始 -->
    <el-card class="box-card">
      <el-row>
        <el-col :span="12">
          <el-radio-group v-model="queryDeptParams.regItemId" @change="registeredItemChange">
            <el-radio-button
              v-for="d in regItemOptions"
              :key="d.regItemId"
              :label="d.regItemId"
              :value="d.regItemId"
            >
              {{ d.regItemName }}
            </el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="12">
          <div style="float:right">
            <span style="margin-left:20px">挂号费:￥{{ queryDeptParams.regItemFee }}</span>
            <el-button type="danger" icon="el-icon-search" :disabled="single" size="small" @click="handleRegistration">挂号收费</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 挂号项目栏结束 -->

    <el-card>
      <el-form ref="queryDeptForm" :model="queryDeptParams" :inline="true" label-width="68px">
        <el-form-item label="所属科室" prop="deptId">
          <el-select
            v-model="queryDeptParams.deptId"
            placeholder="请选择所属科室"
            clearable
            size="small"
            style="width:200px"
          >
            <el-option
              v-for="d in deptOptions"
              :key="d.deptId"
              :label="d.deptName"
              :value="d.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="挂号类型" prop="schedulingType">
          <el-select
            v-model="queryDeptParams.schedulingType"
            placeholder="请选择挂号类型"
            clearable
            size="small"
            style="width:200px"
            @change="registeredItemChange"
          >
            <el-option
              v-for="dict in schedulingTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="挂号时段" prop="subsectionType">
          <el-select
            v-model="queryDeptParams.subsectionType"
            placeholder="请选择挂号时段"
            clearable
            size="small"
            style="width:200px"
          >
            <el-option
              v-for="dict in subsectionTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="挂号时间" prop="schedulingDay">
          <el-date-picker
            v-model="queryDeptParams.schedulingDay"
            size="small"
            style="width:240px"
            value-format="yyyy-MM-dd"
            type="date"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDeptQuery">搜索</el-button>
          <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetDeptQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 部门数据表格开始 -->
      <el-table border :data="deptTableList" highlight-current-row @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="科室ID" align="center" prop="deptId" />
        <el-table-column label="科室名称" align="center" prop="deptName" :formatter="deptIdFormatter" />
        <el-table-column width="150%" type="index" :index="indexNum" label="当前号数" align="center" prop="regNumber" />
      </el-table>
      <!-- 部门数据表格结束 -->
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ids:[],
      // 患者基本信息
      patientParams: {

      },
      // 性别字典库
      sexOptions: [],
      rules: {
        name: [
          { required: true, message: '患者姓名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3|4|5|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
        ]
      },
      // 挂号项目栏
      queryDeptParams: {
        deptId: undefined,
        schedulingType: '1',
        subsectionType: undefined,
        schedulingDay: new Date(),
        regItemId: 1,
        regItemFee: undefined
      },
      // 系统表中 - 挂号费用
      regItemOptions: [],
      // 非单个禁用
      single: true,
      // 部门数据表格
      deptTableList: [],
      // 部门
      deptOptions:[],
      // 选中的收费项目
      multipleSelection:[],
      schedulingTypeOptions:[],
      subsectionTypeOptions:[],
// 当前页号
      numberQuanJu:0,
    }
  },
  created() {
    // 加载性别字典
    this.initSex();
    // 系统表中 - 挂号费用查询
    this.initRegItem();
    // 加载所有部门
    this.initDept();
     // 加载挂号类型 门诊急诊
     this.initschedulingType();
     // 加载挂号时段 上下午+晚上
    this.initSubsectionType();
    // 设置查询时段
    const subsectionType = this.getCurrentTimeType()
    this.queryDeptParams.subsectionType = subsectionType
  },
  methods: {
    // 加载身份证号 & 加载患者信息
    handleIdCardQuery() {
      this.$axios.get("doctor/api/patient/getPatientByIdCard/" + this.patientParams.idCard)
        .then(row => {
          if(row.data.data !=null){
            this.patientParams = row.data.data;
          this.patientParams.age = this.getAge(row.data.data.birthday.substring(0, 10))
          }else{
            this.$message.error("请输入详细信息,完善患者库")
          }

        });
    },
    handleIdCardNull() {
      this.patientParams = {};
    },
    // 加载性别字典
    initSex() {
      this.$axios.get("doctor/system/dictDataByType/sys_user_sex").then(row => {
        this.sexOptions = row.data.data;
      })
    },
    // 系统表中 - 挂号费用查询
    initRegItem() {
      this.$axios.get("doctor/system/getAllRegisteredItems").then(row => {
        this.regItemOptions = row.data.data;
        this.queryDeptParams.regItemId = this.regItemOptions[0].regItemId;
        this.queryDeptParams.regItemName = this.regItemOptions[0].regItemName;
        this.queryDeptParams.regItemFee = this.regItemOptions[0].regItemFee;
      })
    },
    registeredItemChange(id){
      this.regItemOptions.filter(item => {
        if (id === item.regItemId) {
          this.queryDeptParams.regItemId = item.regItemId
          this.queryDeptParams.regItemFee = item.regItemFee
        }
      })
      // 动态显示挂号信息
      if (id === 1 || id === 2) {
        this.queryDeptParams.schedulingType = '1'
      } else {
        this.queryDeptParams.schedulingType = '2'
      }
      // 加载所有部门
     this.initDept();
    },
    // 门诊急诊...切换事件
    schedulingTypeChange(value) {
      this.schedulingType = value
    },

    // 表格选择中行事件
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deptId)
      this.djuserId = selection.map(item => item.userId)
      this.single = selection.length !== 1
    },
    // 挂号收费
    handleRegistration() {
      const tx = this
      tx.$refs['form'].validate(vaid => {
        if (vaid) {
          tx.$confirm('是否确认给【' + this.patientParams.name + '】进行挂号?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            closeOnClickModal: false,
            type: 'waring',
            center: true
          }).then(() => {
            // 取出要挂号的部门
            const deptId = tx.ids[0]
            const userId = tx.djuserId[0]
            // 组装要提交到后台的挂号数据
            const data = { 'patientDto': tx.patientParams, 'registrationDto': {
                deptId: deptId,
                registrationNumber: tx.numberQuanJu+1,
                regItemId: tx.queryDeptParams.regItemId,
                regItemFee: tx.queryDeptParams.regItemFee,
                visitDate: this.moment(tx.queryDeptParams.schedulingDay).format('YYYY-MM-DD'),
                schedulingType: tx.queryDeptParams.schedulingType,
                subsectionType: tx.queryDeptParams.subsectionType,
                userId: userId,
              }}
            // 提交数据到后台
            this.$axios.post("doctor/api/registration/addRegistration",data).then(res => {
              const regId = res.data.data
              tx.$message.success('挂号成功 挂号单号为【' + regId + '】')
              // 清空页面上的数据
              tx.resetDeptQuery()
              tx.patientParams = { sex: '2' }

              tx.$confirm('是否确认给挂号ID为【' + regId + '】的挂号收费?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                closeOnClickModal: false,
                type: 'waring',
                center: true
              }).then(() => {
                this.initRegItem();
                // 重新查询挂号列表
                this.$axios.get("doctor/api/registration/collectFee/"+regId).then(r => {
                  tx.$message.success('收费成功')
                  // tx.getDeptForScheduling2()
                }).catch(() => {
                  tx.$message.error('收费失败')
                })
              }).catch(() => {
                tx.$message.error('收费取消')
              })
            }).catch(() => {
              tx.$message.error('挂号失败')
            })
          }).catch(() => {
            tx.$message.error('挂号已取消')
          })
        }
      })
    },
    //查询排班就诊
    getDeptForScheduling() {
      this.queryDeptParams.schedulingDay = this.moment(this.queryDeptParams.schedulingDay).format('YYYY-MM-DD')
      if(this.queryDeptParams.deptId){
        this.$axios.post("/doctor/api/scheduling/listDeptForScheduling",this.queryDeptParams).then(res => {
        this.deptTableList = res.data.data
      })
      }else{
        this.$message.error("请选择科室")
    }
    },
    getDeptForScheduling2() {
      this.queryDeptParams.schedulingDay = this.moment(this.queryDeptParams.schedulingDay).format('YYYY-MM-DD')
        this.$axios.post("/doctor/api/scheduling/listDeptForScheduling",this.queryDeptParams).then(res => {
        this.deptTableList = res.data.data
      })
    },
    indexNum(index){
     this.$axios.get("/doctor/api/registration/getRegistrationNumber/"+this.queryDeptParams.deptId).then(row=>{
        this.numberQuanJu = row.data.data;
      });
      return this.numberQuanJu +1;
    },
    // 下 - 搜索
    // 查询
    handleDeptQuery() {
      this.getDeptForScheduling()
    },
    // 下 - 重置
    resetDeptQuery() {
      // 设置查询时段
      this.queryDeptParams= {
        schedulingDay:new Date(),
        schedulingType:'1',
        subsectionType: this.getCurrentTimeType()
      };
      this.reset1Form('queryDeptForm')
      this.deptTableList=[]
      this.initRegItem()
    },
    // 加载所有部门
    initDept() {
            this.$axios.get("doctor/system/deptList").then(row => {
                this.deptOptions = row.data.data;
            })
        },
        // 解析 所有部门
    deptIdFormatter(row) {
      let v = row.deptId;
      for (let i = 0; i < this.deptOptions.length; i++) {
        if (this.deptOptions[i].deptId == v) {
          return this.deptOptions[i].deptName;
        }
      }
      return "";
    },
    // 加载挂号类型 门诊急诊
    initschedulingType() {
      this.$axios.get("doctor/system/dictDataByType/his_scheduling_type").then(row => {
        this.schedulingTypeOptions = row.data.data;
      })
    },
    // 解析 加载挂号类型
    schedulingTypeFormatter(row) {
      let v = row.schedulingType;
      return this.formatDict(this.schedulingTypeOptions, v);
    },
    // 加载挂号时段 上下午+晚上
    initSubsectionType() {
      this.$axios.get("doctor/system/dictDataByType/his_subsection_type").then(row => {
        this.subsectionTypeOptions = row.data.data;
      })
    },
    // 解析 加载挂号时段
    subsectionTypeFormatter(row) {
      let v = row.subsectionType;
      return this.formatDict(this.subsectionTypeOptions, v);
    },

  },
  watch: {
    patientParams: {
      handler: function() {
        if (this.patientParams.birthday !== undefined) {
          this.patientParams.age = this.getAge(this.patientParams.birthday.substring(0, 10))
        }
      },
      deep: true
    }
  },
}
</script>

<style>
.box-card {
  padding: 0px;
  margin: 0px;
  margin-bottom: 8px;
}
</style>
